package com.rlyy.basic.resolver.exception;

import org.springframework.core.MethodIntrospector;
import org.springframework.core.annotation.AnnotatedElementUtils;
import org.springframework.util.Assert;
import org.springframework.util.ReflectionUtils;
import org.springframework.web.bind.annotation.ExceptionHandler;

import java.lang.reflect.Method;
import java.util.*;

/**
 * 获取异常处理目标方法解析器
 *
 * @author yuanqinglong
 * @since 2020/11/30 9:26
 */
public class MyExceptionHandlerMethodResolver {

    public static final ReflectionUtils.MethodFilter EXCEPTION_HANDLER_METHODS = method ->
            AnnotatedElementUtils.hasAnnotation(method, ExceptionHandler.class);

    /**
     * 异常类型和处理此异常的方法映射
     */
    private final Map<Class<? extends Throwable>, Method> mappedMethods = new HashMap<>(16);


    /**
     *  获取异常处理类中所有标注@ExceptionHandler注解的方法
     */
    public MyExceptionHandlerMethodResolver(Class<?> handlerType) {
        for (Method method : MethodIntrospector.selectMethods(handlerType, EXCEPTION_HANDLER_METHODS)) {
            // 获取这个异常处理方法 配置的异常类信息
            for (Class<? extends Throwable> exceptionType : detectExceptionMappings(method)) {
                // 添加异常信息对应处理方法的映射关系map中
                this.mappedMethods.put(exceptionType, method);
            }
        }
    }

    /**
     * 检查异常处理方法处理的异常类
     */
    private List<Class<? extends Throwable>> detectExceptionMappings(Method method) {
        ExceptionHandler ann = AnnotatedElementUtils.findMergedAnnotation(method, ExceptionHandler.class);
        Assert.state(ann != null, "没有找到@ExceptionHandler注解");
        // 获取@ExceptionHandler配置拦截的异常类
        List<Class<? extends Throwable>> result = new ArrayList<>(Arrays.asList(ann.value()));
        if (result.isEmpty()) {
            // 如果没配置 从异常处理方法的参数中获取
            for (Class<?> paramType : method.getParameterTypes()) {
                if (Throwable.class.isAssignableFrom(paramType)) {
                    result.add((Class<? extends Throwable>) paramType);
                }
            }
        }
        // 如果都没配置拦截的异常 跑出异常
        if (result.isEmpty()) {
            throw new IllegalStateException("没有找到异常处理器");
        }
        return result;
    }

    /**
     * 获取抛出的异常对应的处理方法
     *
     * @param exceptionType 抛出的异常信息
     * @return 返回对应的处理方法
     */
    public Method getMappedMethod(Class<? extends Throwable> exceptionType) {
        List<Class<? extends Throwable>> matches = new ArrayList<>();
        // 通过抛出的异常获取对应的异常处理方法
        for (Class<? extends Throwable> mappedException : this.mappedMethods.keySet()) {
            if (mappedException.isAssignableFrom(exceptionType)) {
                matches.add(mappedException);
            }
        }
        if (matches.isEmpty()) {
            return null;
        }
        // 如果抛出的异常匹配到多个处理类 获取异常范围最小的来处理
        matches.sort(new MyExceptionDepthComparator(exceptionType));
        // 返回异常对应的处理方法
        return this.mappedMethods.get(matches.get(0));

    }


    public boolean hasExceptionMappings() {
        return !mappedMethods.isEmpty();
    }
}
